package com.scau.clothes.service.impl;

import com.scau.clothes.dao.UserDao;
import com.scau.clothes.pojo.User;
import com.scau.clothes.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    StringRedisTemplate redisTemplate;
    private static final String LOGOUT = "LOGOUT";

    @Override
    public void addUser(User user) {
        userDao.addUser(user);
    }

    @Override
    public User getUserByUserId(int userId, String password) {
        return null;
    }

    @Override
    public User getUserByEmail(String email, String password) {
        return null;
    }

    @Override
    public User login(String info, String password) {
        User user = null;
        try {
            int i = Integer.parseInt(info);
            user = userDao.getUserByUserId(i,password);
        } catch (NumberFormatException e) {
            user=userDao.getUserByEmail(info, password);
        }
        if(user==null){
            return null;
        }
        //从logout黑名单中剔除
        redisTemplate.opsForHash().delete(LOGOUT,user.getId()+"");
        return user;
    }

    @Override
    public String getEmailById(int userId) {
        return userDao.getEmailById(userId);
    }

    @Override
    public void logout(int userId) {
        redisTemplate.opsForHash().put(LOGOUT,userId+"",userId+"");
    }

    @Override
    public boolean isInLogoutList(int userId) {
        return redisTemplate.opsForHash().hasKey(LOGOUT, userId+"");
    }

    @Override
    public boolean register(User user,String password2) {
        if(user.getPasswd().equals(password2)){
            userDao.addUser(user);
            return true;
        }
        else {
            return false;
        }
    }
}
